'''
Created on 5 Nov 2014

@author: User
'''
from data_api import DataAPI;
import numpy as np;
import urllib2;
import matplotlib.dates as mdates;
from datetime import datetime
from main.data.my_enums import Timeframe
from main.model.prices import Prices

class YahooAPI(DataAPI):
    '''
    classdocs
    '''
    url='http://ichart.yahoo.com/table.csv?s={code}&a={ms}&b={ds}&c={ys}&d={me}&e={de}&f={ye}&g={tf}&ignore=.csv';

        
    def downloadHistorical(self,code,ys,ms=1,ds=1,ye=2035,me=1,de=1,tf=Timeframe.DAILY):
        """ Download historical market data"""
        
        # Compensate for yahoo starting dates from 0
        ms-=1;
        me-=1;
        
        filep = urllib2.urlopen(self.url.format(code=code,ms=ms,ds=ds,ys=ys,me=me,de=de,ye=ye,tf=tf))
        title = filep.readline().strip().split(",");
        filep = filep.readlines();

        dates,openp,highp,lowp,ignore,volume,closep =  np.loadtxt(filep,unpack=True,delimiter=",",converters={0:mdates.strpdate2num("%Y-%m-%d")});
        
        ''' 
        for i in range(len(dates)):
            dt = datetime.fromordinal(int(dates[i]));
            
            print dt.strftime("%Y-%m-%d"),openp[i],highp[i],lowp[i],closep[i],volume[i];
       '''
        return Prices(dates,openp,highp,lowp,closep,volume,tf);
    
    def downloadLatest(self,code):
        """ Download the most up to date market data"""
        return;
        
        